package com.jule.teenpatti.game.network.protocol.reqs;

import JoloProtobuf.GameSvr.JoloGame;
import com.jule.core.common.log.LoggerUtils;
import com.jule.teenpatti.base.enums.ErrorCodeEnum;
import com.jule.teenpatti.base.enums.GameConst;
import com.jule.teenpatti.game.dao.DBUtil;
import com.jule.teenpatti.game.dao.bean.TipHistoryModel;
import com.jule.teenpatti.game.model.PlayerInfo;
import com.jule.teenpatti.game.network.protocol.ClientReq;
import com.jule.teenpatti.game.network.protocol.acks.JoloGame_RewardCroupierAck_50050;
import com.jule.teenpatti.game.play.AbstractTable;
import com.jule.teenpatti.game.service.TableService;
import com.jule.teenpatti.game.utils.log.TableLogUtil;
import com.jule.teenpatti.game.vavle.notice.NoticeBroadcastMessages;
import com.jule.teenpatti.log.service.LogReasons;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JoloGame_RewardCroupierReq_50050 extends ClientReq {
    private long time;

    public JoloGame_RewardCroupierReq_50050(int functionId) {
        super(functionId);
    }

    private JoloGame.JoloGame_RewardCroupierReq req;

    @Override
    public void readPayLoadImpl(ByteBuf buf) throws Exception {
        time = System.currentTimeMillis();
        byte[] blob = new byte[buf.readableBytes()];
        buf.readBytes(blob);
        req = JoloGame.JoloGame_RewardCroupierReq.parseFrom(blob);
        AbstractTable table = TableService.getInstance().getTable(header.gameId + "", req.getRoomId(), req.getTableId());
        if (null != table) {
            this.setTable(table);
        } else {
            log.error("桌子不存在,roomId->" + req.getRoomId() + ", tableId->" + req.getTableId());
        }
    }

    @Override
    public void processImpl() throws Exception {
        log.debug("收到消息-> " + functionId + " reqNum-> " + header.reqNum + "msg ->" + req.toString());
        String userId = req.getUserId();
        try {
            AbstractTable table = getTable();
            if (table == null) {
                log.info("table is null , userId = " + userId);
                return;
            }

            int tipVaule = table.getRoomConfig().getTipValue();
            log.info("tipValue:" + tipVaule);
            PlayerInfo player = table.getPlayer(userId);
            JoloGame.JoloGame_RewardCroupierAck.Builder ack = JoloGame.JoloGame_RewardCroupierAck.newBuilder();
            ack.setRoomId(table.getRoomId()).setTableId(table.getTableId()).setUserId(userId);
            ack.setTipValue(tipVaule);
            //没在桌上
            if (!table.getInGamePlayersByPlayerId().containsKey(userId)) {
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50050_1.getCode());
                ctx.writeAndFlush(new JoloGame_RewardCroupierAck_50050(ack.build(), header));
                return;
            }
            //判断游戏币是否足够
            //用户信息：现在从数据库获取，以后可优化成从缓存获取
            //User user = DBUtil.selectByPrimaryKey(userId);
            if (null == player) {
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50050_2.getCode());
                ctx.writeAndFlush(new JoloGame_RewardCroupierAck_50050(ack.build(), header));
                return;
            }

            double playScoreStore = player.getPlayScoreStore();//玩家牌桌上积分的携带量

            if (playScoreStore < tipVaule) {
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50050_3.getCode());
                ctx.writeAndFlush(new JoloGame_RewardCroupierAck_50050(ack.build(), header));
                return;
            }

            //player.setPlayScoreStore(playScoreStore - tipVaule);
            player.minusPlayScoreStore(tipVaule, LogReasons.CommonLogReason.GAME_DEALER_REWARDS);
            ack.setCurrPlayScore(player.getPlayScoreStore()).setResult(1).setTipValue(tipVaule);
            ctx.writeAndFlush(new JoloGame_RewardCroupierAck_50050(ack.build(), header));

            TableLogUtil.tip(functionId, "rewardCroupier", userId, player.getNickName(), table.getPlayType() + "",
                    table.getRoomId(), table.getTableId(), tipVaule);

            //tipRecord(table, userId, "");
            //发送通知
            NoticeBroadcastMessages.moneyChangeNotice(table,userId,player.getPlayScoreStore());

            //打赏荷官

            NoticeBroadcastMessages.rewardCroupier(table, userId);
            long timeMillis = System.currentTimeMillis() - time;
            if (timeMillis > GameConst.COST_TIME) {
                LoggerUtils.performance.info("RewardCroupierReq_50050,cost time:{},req:{}", timeMillis, req.toString());
            }
        } catch (Exception ex) {
            log.error("SendNotice ERROR：", ex);
        } finally {
        }
    }

    private void tipRecord(AbstractTable tableInfo, String userId, String targetUserId) {
        TipHistoryModel record = new TipHistoryModel();
        record.setPlay_type(1);
        record.setRoom_id(tableInfo.getRoomId());
        record.setTable_id(tableInfo.getTableId());
        record.setTarget_user_id(targetUserId);
        record.setTip_value(tableInfo.getRoomConfig().getTipValue());
        record.setUser_id(userId);
        int result = DBUtil.insertTipHistory(record);
        log.info("insert tip_history result:" + result);
    }

}
